package model

import (
	"bytes"
	"database/sql/driver"
	"errors"
	"fmt"
	"github.com/shopspring/decimal"
	"time"
)

type Decimal = decimal.Decimal

// LocalTime 自定义数据类型1开始
type LocalTime struct {
	time.Time
}

func (t LocalTime) MarshalJSON() ([]byte, error) {
	//格式化秒
	seconds := t.UnixNano() / 1e6 // 毫秒时间
	if seconds > 0 {
		return []byte(fmt.Sprintf("%d", seconds)), nil
	} else {
		return []byte("-1"), nil
	}
}

func (t LocalTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

func (t *LocalTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = LocalTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

// LocalTime 自定义数据类型1结束

// JSON 自定义JSON数据类型
type JSON []byte

func (j JSON) Value() (driver.Value, error) {
	if j.IsNull() {
		return nil, nil
	}
	return string(j), nil
}
func (j *JSON) Scan(value interface{}) error {
	if value == nil {
		*j = nil
		return nil
	}
	s, ok := value.([]byte)
	if !ok {
		errors.New("invalid Scan Source")
	}
	*j = append((*j)[0:0], s...)
	return nil
}
func (m JSON) MarshalJSON() ([]byte, error) {
	if m == nil {
		return []byte("null"), nil
	}
	return m, nil
}
func (m *JSON) UnmarshalJSON(data []byte) error {
	if m == nil {
		return errors.New("null point exception")
	}
	*m = append((*m)[0:0], data...)
	return nil
}
func (j JSON) IsNull() bool {
	return len(j) == 0 || string(j) == "null"
}
func (j JSON) Equals(j1 JSON) bool {
	return bytes.Equal([]byte(j), []byte(j1))
}

/**
var ticketIdList = make([]int64, 0)
	fmt.Println(reflect.TypeOf(scoreProject.TicketIDList), "????")
	value, _ := scoreProject.TicketIDList.MarshalJSON()
	if err := json.Unmarshal(value, &ticketIdList); err != nil {
		utils.Fail(ctx, "你传递的scoreProjectId错误")
		return
	}
*/
